<template>
  <Nuxt-Layout>
    <el-breadcrumb class="my-crumb">
      <el-breadcrumb-item v-for="(item, index) in crumbData" :key="index">
        <a :href="item.href">{{ item.title }}</a>
      </el-breadcrumb-item>
    </el-breadcrumb>
    <div class="con">
      <div class="con-cen">
        <div class="con-cen-info">
          <div class="info-top">
            <el-image class="info-top-left" :src="infoData.imgs && infoData.imgs.length > 0
              ? infoData.imgs[0]
              : ''
              " fit="cover" alt="" />
            <div class="info-top-center">
              <div class="info-top-center-subject">
                科目名称：{{ infoData.subject ? infoData.subject.name : "-" }}
              </div>
              <div class="info-top-center-title">
                课程名称：{{ infoData.title }}
              </div>
              <div class="info-top-center-amount">
                费用：<span class="big" :class="infoData.amount > 0 ? '' : 'big-remove'">{{ infoData.amount > 0 ? infoData.amount : '免费' }}</span>
              </div>
              <div class="info-top-center-tool">
                <a class="el-button el-button--warning" href="/login" v-if="!isLogin">登录学习</a>
                <el-button type="danger" :disabled="buyCourseDisabled" v-if="isLogin && !infoData.purchased"
                  @click="buyCourseFn">购买课程</el-button>
                <a class="el-button el-button--primary" :href="detailsUrl" v-if="!isLogin || isLogin && !infoData.purchased">预览课程</a>
                <a class="el-button el-button--success" :href="detailsUrl"
                  v-if="isLogin && infoData.purchased">开始学习</a>
              </div>
            </div>
            <div class="info-top-right">
              <div class="info-top-right-star">
                推荐星级：<el-rate v-model="infoData.starLevel" disabled show-score text-color="#ff9900" />
              </div>
              <div class="info-top-right-score">
                评分指数：{{ infoData.scoreLevel }}
              </div>
            </div>
          </div>
          <hr class="info-hr" />
          <el-descriptions :column="4" style="margin-top: 20px">
            <el-descriptions-item label="章节数量">{{ infoData.totalChapter }}</el-descriptions-item>
            <el-descriptions-item label="视频数量">{{ infoData.totalVideo }}</el-descriptions-item>
            <el-descriptions-item label="总学时">{{ (infoData.totalHours).toFixed(1) }}</el-descriptions-item>
            <el-descriptions-item label="总时长">{{ convertSecondsToHMS(infoData.totalDuration) }}</el-descriptions-item>
            <el-descriptions-item label="内容简介">{{
              infoData.brief
            }}</el-descriptions-item>
          </el-descriptions>
        </div>
        <div class="con-cen-row">
          <div class="con-cen-row-left">
            <div class="left-details">
              <el-tabs v-model="tabsValue" @tab-click="handleTabsFn">
                <el-tab-pane label="课程详情" :name="1">
                  <div class="left-details-con" v-html="infoData.content"></div>
                </el-tab-pane>
                <el-tab-pane label="课程留言" :name="2">
                  <ul class="left-details-message">
                    <template v-for="item in messageData" :key="item.id">
                      <li class="left-details-message-li">
                        <p class="left-details-message-li-name">
                          <span>留言者：{{ item.commentName || "-" }}</span>
                          <el-button type="primary" size="small" @click="replyOpen(item)">回复</el-button>
                        </p>
                        <p class="left-details-message-li-con">
                          <span style="padding-right: 10px">留言内容：</span>
                          <span style="flex: 1; overflow: hidden">{{
                            item.commentContent
                            }}</span>
                          <span style="padding-left: 10px">{{
                            item.commentTime
                            }}</span>
                        </p>
                      </li>
                      <li class="left-details-message-li" v-for="(ite, ind) in item.replys" :key="ind"
                        style="margin-left: 40px">
                        <p class="left-details-message-li-name">
                          回复者：{{ ite.replyName || "-"
                          }}<el-tag size="small" :type="ite.type < 1 ? 'danger' : 'success'"
                            style="margin-left: 10px">{{ ite.type < 1 ? "机构" : "用户" }}</el-tag>
                        </p>
                        <p class="left-details-message-li-con">
                          <span style="padding-right: 10px">回复内容：</span>
                          <span style="flex: 1; overflow: hidden">{{
                            ite.replyContent
                            }}</span>
                          <span style="padding-left: 10px">{{
                            ite.replyTime
                            }}</span>
                        </p>
                      </li>
                    </template>
                    <el-empty v-show="messageData.length < 1" />
                  </ul>
                  <div class="pagin">
                    <el-pagination background layout="prev, pager, next, total" :page-size="messageForm.pageSize"
                      :total="messageTotal" v-model:current-page="messageForm.pageNum" @change="pageChangeFn"
                      hide-on-single-page />
                  </div>
                  <div class="left-details-release">
                    <el-input type="textarea" v-model="releaseForm.commentContent" rows="5" placeholder="请输入留言内容..."
                      autocomplete="off" />
                    <a class="el-button el-button--warning" href="/login" style="margin-top: 10px"
                      v-if="!isLogin">登录</a>
                    <el-button type="primary" style="margin-top: 10px" :disabled="releaseDisabled" @click="releaseFn"
                      v-else>发送</el-button>
                  </div>
                </el-tab-pane>
              </el-tabs>
            </div>
          </div>
          <div class="con-cen-row-right">
            <p class="right-title">讲师信息</p>
            <div class="right-info" v-for="item in infoData.teachers" :key="item.id">
              <el-image class="right-info-avatar" :src="item.portrait" fit="cover" :alt="item.name" />
              <div class="right-info-item">
                <p class="right-info-item-title">{{ item.name }}</p>
                <p class="right-info-item-brief">
                  {{ item.brief || "这位讲师很懒，还没有填写自我介绍哦~" }}
                </p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <ReplyForm :visible="replyVisible" :forms="replyForm" @pick="replyPickFn" />
  </Nuxt-Layout>
</template>

<script setup>
import { getLessonInfoApi, getCommentApi, addCommentApi, replyCommentApi, lessonPurchaseApi } from "~/server/api";
import { convertSecondsToHMS, isEmpty } from "~/utils/utils";
import { useCountStore } from "~/store/counter.js";
import ReplyForm from "./replyform";
useCountStore().$patch({ indexActive: 3 });
const crumbData = ref([
  { title: '首页', href: '/' },
  { title: '课程中心', href: '/curriculum' },
])
// TDK
const prevHost = useRequestHeaders()["x-forwarded-proto"];
const host = useRequestHeaders()["host"];
const fullPath = useRoute()["fullPath"];
const seoTitle = ref("技考邦_课程详情");
const seoKeywords = ref("技考邦,课程详情");
const seoDescription = ref("技考邦，课程详情。");
const isLogin = ref(!isEmpty(useRoute().meta.userinfo) ? true : false);
const detailsUrl = ref("");
const courseId = useRoute().params.courseId || "";
const tabsValue = ref(1)
// 验证路由
definePageMeta({
  validate: async (route) => {
    return /^1\d{5,}$/.test(route.params.courseId);
  }
})
const courseVideoId = useRoute().params.videoId || "";
// 获取详情
const infoData = ref({});
const getInfo = async () => {
  let { data: infoRes } = await useAsyncData("getLessonInfoApi", () =>
    useServerRequest(getLessonInfoApi, {
      method: "get",
      params: { courseId }
    })
  );
  if (infoRes.value && infoRes.value.errno === 0 && infoRes.value.result) {
    infoData.value = infoRes.value.result;
    crumbData.value.push({ title: infoData.value.title, href: 'javascript:;' })
    // 章节 默认跳转第一章节
    if (infoData.value.chapters && infoData.value.chapters.length > 0) {
      detailsUrl.value = `/curriculum_details/${infoData.value.id}-${infoData.value.chapters[0].id}.html`;
      if (infoData.value.chapters[0].videos && infoData.value.chapters[0].videos.length > 0) {
        detailsUrl.value = `/curriculum_details/${infoData.value.id}-${infoData.value.chapters[0].id}-${infoData.value.chapters[0].videos[0].id}.html`;
      }
    }
    // 读取上次观看章节及视频
    if (infoData.value.currentChapterId && infoData.value.currentVideoId) {
      detailsUrl.value = `/curriculum_details/${infoData.value.id}-${infoData.value.currentChapterId}-${infoData.value.currentVideoId}.html`;
    }
    // 修改TDK
    seoTitle.value = infoData.value.title;
    seoDescription.value = infoData.value.brief;
    return false;
  }
  showError({ statusCode: 404, statusMessage: `Page not found: ${useRoute().path}` });
};
getInfo()
// 选项卡
const handleTabsFn = (e) => {
  tabsValue.value = e.props.name;
}
// 课程留言
const messageForm = ref({
  pageNum: parseInt(useRoute().query.p) || 1,
  pageSize: 5,
  courseId,
  courseVideoId: "",
});
const messageData = ref([]);
const messageTotal = ref(0);
const getMessage = async () => {
  let { data: messageRes } = await useAsyncData("getCommentApi", () =>
    useServerRequest(getCommentApi, {
      method: "post",
      body: JSON.stringify(messageForm.value),
    })
  );
  if (messageRes.value && messageRes.value.errno === 0) {
    messageData.value = messageRes.value.result.list || [];
    messageTotal.value = messageRes.value.result.total;
    return false;
  }
};
getMessage();
// 分页
const pageChangeFn = (val) => {
  let href = `/curriculum_details/${courseId}.html?p=${val}`;
  getMessage();
  useRouter().push(href);
};
// 购买课程
const buyCourseDisabled = ref(false);
const buyCourseFn = async () => {
  buyCourseDisabled.value = true;
  let { errno, errmsg, result } = await useServerRequest(lessonPurchaseApi, {
    method: "post",
    body: JSON.stringify({
      id: infoData.value.id
    }),
  });
  if (errno === 0 && !result) {
    ElMessage({
      message: "购买成功",
      type: "success",
    });
    infoData.value.purchased = true;
    buyCourseDisabled.value = false;
    return false;
  }
  if (errno === 0 && result) {
    window.location.href = `/trading/${courseId}.html`;
  }
  buyCourseDisabled.value = false;
};
// 发送留言
const releaseDisabled = ref(false);
const releaseForm = ref({
  courseId,
  courseVideoId,
  commentContent: "",
});
const releaseFn = async () => {
  if (releaseForm.value.commentContent == "") {
    ElMessage({
      message: "请输入回复内容",
      type: "warning",
    });
    return false;
  }
  releaseDisabled.value = true;
  let { errno, errmsg, result } = await useServerRequest(addCommentApi, {
    method: "post",
    body: JSON.stringify(releaseForm.value),
  });
  if (errno === 0) {
    ElMessage({
      message: "发送成功",
      type: "success",
    });
    getMessage();
    releaseForm.value.commentContent = "";
    releaseDisabled.value = false;
    return false;
  }
  releaseDisabled.value = false;
};
// 回复
const replyVisible = ref(false);
const replyForm = ref({});
const replyOpen = (val) => {
  replyForm.value.id = val.id;
  replyForm.value.replyContent = "";
  replyVisible.value = true;
};
const replyPickFn = async (e) => {
  replyVisible.value = e.visible;
  if (e.form) {
    if (e.form.replyContent == "") {
      ElMessage({
        message: "请输入回复内容",
        type: "warning",
      });
      return false;
    }
    let { errno, errmsg, result } = await useServerRequest(replyCommentApi, {
      method: "post",
      body: JSON.stringify(e.form),
    });
    if (errno === 0) {
      ElMessage({
        message: "回复成功",
        type: "success",
      });
      getMessage();
      return false;
    }
  }
};
// seo
useSeoMeta({
  title: seoTitle,
  keywords: seoKeywords,
  description: seoDescription,
  ogTitle: seoTitle,
  ogDescription: seoDescription,
  ogType: "article",
  ogUrl: `${prevHost}://${host}${fullPath}`,
});
</script>

<style lang="less">
.info-top-right-star {
  .el-rate .el-rate__icon {
    margin-right: 2px;
  }

  .el-rate__text {
    margin-left: 5px;
  }
}

.con-cen-video-right {
  .el-collapse-item__header.is-active {
    color: #409eff;
  }
}

.left-details {

  .el-tabs__nav-wrap:after {
    content: unset;
  }

  .el-tabs__item {
    color: #666666;
    font-size: 18px;
    font-weight: 700;

    &.is-active {
      color: #409eff;
    }
  }
}
</style>
<style lang="less" scoped>
.con {
  padding: 20px 0;
  min-height: calc(100vh - 454px);

  &-cen {
    width: 1200px;
    margin: 0 auto;

    &-info {
      background: #ffffff;
      border-radius: 10px;
      border: 1px solid #eaeae6;
      padding: 20px;

      .info-top {
        display: flex;

        &-left {
          width: 285px;
          height: 165px;
          border-radius: 10px;
          margin-right: 27px;
        }

        &-center {
          flex: 1 0;
          overflow: hidden;
          display: flex;
          flex-wrap: wrap;
          align-content: space-between;

          &-subject {
            flex: 100%;
            font-weight: bold;
            font-size: 16px;
            color: #666666;
          }

          &-title {
            flex: 100%;
            font-weight: bold;
            font-size: 16px;
            color: #666666;
            margin-top: 10px;
          }

          &-amount {
            flex: 100%;
            margin-top: 10px;
            font-weight: bold;
            font-size: 16px;
            color: #666666;

            .big {
              color: #ff6c00;
              font-size: 30px;

              &::before {
                content: "￥";
                font-size: 16px;
              }

              &.big-remove {
                font-size: 16px;
                color: #666;

                &::before {
                  content: none;
                }
              }
            }
          }

          &-tool {
            flex: 100%;
            margin-top: 10px;
          }
        }

        &-right {
          &-star {
            font-size: 14px;
            color: #666666;
            display: flex;
            align-items: center;
          }

          &-score {
            font-size: 14px;
            color: #666666;
            margin-top: 10px;
          }
        }
      }

      .info-hr {
        height: 1px;
        border: 0;
        background: #eaeae6;
        margin: 20px 0 0 0;
      }

      :deep(.label-color-red),
      :deep(.content-color-red) {
        color: #ff3f29;
      }
    }

    &-row {
      margin-top: 20px;
      display: flex;
      align-items: flex-start;
      justify-content: space-between;

      &-left {
        width: 860px;
      }

      &-right {
        width: 320px;
        background: #ffffff;
        border-radius: 10px;
        border: 1px solid #eaeae6;
        padding: 20px;

        .right-title {
          font-weight: bold;
          font-size: 18px;
          color: #666666;
        }

        .right-info {
          margin-top: 20px;
          display: flex;
          align-items: flex-start;

          &-avatar {
            width: 80px;
            height: 100px;
            background: #cccccc;
            border-radius: 5px;
            margin-right: 20px;
          }

          &-item {
            flex: 1;
            overflow: hidden;

            &-title {
              font-weight: bold;
              font-size: 14px;
              color: #666666;
            }

            &-brief {
              font-size: 14px;
              margin-top: 10px;
              color: #666666;
            }
          }
        }
      }
    }

    &-video {
      background: #ffffff;
      border-radius: 10px;
      border: 1px solid #eaeae6;
      padding: 20px;
      display: flex;
      flex-wrap: wrap;
      align-items: stretch;

      &-title {
        flex: 100%;
        font-weight: bold;
        font-size: 18px;
        margin: 0 0 20px 0;
        line-height: 32px;
      }

      &-left {
        margin-right: 20px;
        background-color: #000;
        overflow: hidden;
        position: relative;

        .video-tool {
          position: absolute;
          right: 0;
          bottom: 0;
          left: 0;
          z-index: 99;
          padding: 10px;
          background: linear-gradient(transparent, #000);
          display: flex;
          align-items: center;

          &-icon {
            color: #fff;
            font-size: 28px;
            cursor: pointer;
          }

          &-slider {
            flex: 1;
            margin: 0 10px;
          }

          &-time {
            padding: 0 10px;
            color: #fff;
          }

          &-icons {
            width: 26px;
            height: 26px;
            position: relative;
            cursor: pointer;

            &-icon {
              color: #fff;
              font-size: 14px;
              font-weight: bold;
              position: absolute;

              &:nth-child(1) {
                top: 0;
                left: 0;
              }

              &:nth-child(2) {
                top: 0;
                right: 0;
              }

              &:nth-child(3) {
                right: 0;
                bottom: 0;
              }

              &:nth-child(4) {
                bottom: 0;
                left: 0;
              }
            }
          }
        }
      }

      &-right {
        flex: 1;

        &-title {
          font-weight: bold;
          font-size: 18px;
          height: 20px;
          line-height: 20px;
        }

        .el-button+.el-button {
          margin-left: 0;
        }

        .videos-btn {
          width: 100%;
          justify-content: flex-start;

          &-text {
            text-align: left;
            flex: 1;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            padding-right: 30%;
          }
        }
      }
    }

    &-info {
      margin-top: 20px;
      background: #ffffff;
      border-radius: 10px;
      border: 1px solid #eaeae6;

      &-title {
        font-weight: bold;
        font-size: 18px;
      }

      &-desc {
        margin-top: 20px;
        display: flex;
        align-items: flex-start;

        &-li {
          margin-right: 20px;
          font-size: 16px;
          color: #666666;

          strong {
            color: #666666;
            font-size: 16px;
          }
        }
      }

      &-notice {
        height: 50px;
        background: #ffeded;
        display: flex;
        align-items: center;
        justify-content: flex-start;
        padding: 0 16px;
        margin-top: 10px;

        .notice-icon {
          color: #ff0000;
          margin-right: 16px;
          font-size: 17px;
        }

        .notice-text {
          font-size: 14px;
        }
      }
    }
  }
}

.left-details {
  padding: 20px;
  background: #ffffff;
  border-radius: 10px;
  border: 1px solid #eaeae6;

  &-title {
    font-weight: bold;
    font-size: 18px;
    color: #666666;
  }

  &-con {
    margin-top: 20px;

    img {
      max-width: 100%;
    }
  }

  &-message {
    &-li {
      border-bottom: 1px solid #eaeae6;
      padding: 20px 0;

      &-name {
        font-size: 15px;
        display: flex;
        align-items: center;
        display: flex;
        align-items: center;
        justify-content: space-between;
      }

      &-con {
        margin-top: 5px;
        font-size: 14px;
        color: #666;
        display: flex;
        align-items: flex-start;
      }

      &:last-child {
        border-bottom: 0;
        padding-bottom: 0;
      }
    }
  }

  &-release {
    margin-top: 20px;
  }
}

.pagin {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

p {
  margin: 0;
}
</style>
